class Vue{
    constructor(options){
        this.$el=document.querySelector(options.el)
        this.$data=options.data
        this.compileTemplate(this.$el, this.$data)
    }
    checkShouldRender(cur_elem, cur_node_data) {
        const shouldRenderDataKey = cur_elem.getAttribute("v-if");
        const shouldRender = shouldRenderDataKey == undefined || cur_node_data[shouldRenderDataKey];
        return shouldRender;
    }
    checkIsVForElement(cur_elem) {
        const vForStr = cur_elem.getAttribute("v-for");
        return vForStr != undefined;
    }
    compileVForElement(cur_elem, cur_node_data) {
        const reg = /\s*(.*)\s+in\s+(.*)/;
        const vForStr = cur_elem.getAttribute("v-for");
        const match_res_arr = vForStr.match(reg);
        if (!Array.isArray(match_res_arr) || match_res_arr.length != 3) {
            throw "v-for syntax parse ERROR";
        }
        const [_, item_key, arr_key] = match_res_arr;
        const arr_data = cur_node_data[arr_key];
        if (!Array.isArray(arr_data) || !match_res_arr.length) {
            throw "v-for data is not Array";
        }
        const fragment = new DocumentFragment();
        for (const item_data of arr_data) {
          const new_item = cur_elem.cloneNode(true);
          this.compileTemplate(new_item, {
            cur_node_data,
            [item_key]: item_data,
          });
          fragment.append(new_item);
        }
        cur_elem.replaceWith(fragment);
    }
    // 模板解析
    compileTemplate(node, cur_node_data){
        [...node.childNodes].forEach((item,index)=>{
            // 元素节点
            if(item.nodeType==Node.ELEMENT_NODE){
                if (!this.checkShouldRender(item, cur_node_data)) {
                    node.removeChild(item);
                }
                if (this.checkIsVForElement(item)) {
                    this.compileVForElement(item, cur_node_data);
                } else {
                    this.compileTemplate(item, cur_node_data)
                }
            }
            // 这是文本节点，如果有{{}}就替换成数据
            else if(item.nodeType==Node.TEXT_NODE){
                let reg=/\{\{(.*?)\}\}/g
                let text=item.textContent
                // 给节点赋值
                item.textContent=text.replace(reg,(match,vmKey)=>{
                    vmKey=vmKey.trim()
                    return cur_node_data[vmKey]
                })
            }
        })
    }
}